#include "clientnetengine.h"
#include "connectmsg.h"
#include "connectreplymsg.h"

#include <QtDebug>
#include <QDataStream>
#include <QMutexLocker>

CClientNetEngine::CClientNetEngine(QAbstractSocket *pSock)
		: m_pSocket(pSock)
{
}

void CClientNetEngine::connectToServer(QString strUsername, QString strPassowrdHash)
{
	// create connection message:
	CConnectMsg msg;
	msg.setUsername(strUsername);
	msg.setPassword(strPassowrdHash);

	QDataStream ds(m_pSocket);
	QString strError;

	if (!msg.setMsg(ds, &strError))
	{
		emit commsError(QString("Error while trying to connect to server: '%1'").arg(strError));
		return;
	}

	CNetMsg *pMsg =0;
	pMsg = CNetMsg::getMsg(ds, &strError);
	if (pMsg && pMsg->getType() == CNetMsg::MSG_TYPE_CONNECT_REPLY)
	{
		queueMessage(pMsg);
	}
	else if (pMsg)
	{
		emit commsError("Unexpected return message type!");
	}
	else
	{
		emit commsError(QString("Error while waiting for server reply: '%1'").arg(strError));
	}
}


int CClientNetEngine::getMsgCount()
{
	QMutexLocker lock(&m_queueMutex);

	return m_messages.count();
}

CNetMsg *CClientNetEngine::getMessage()
{
	QMutexLocker lock(&m_queueMutex);

	return m_messages.head();
}

void CClientNetEngine::queueMessage(CNetMsg *p)
{
	{
		QMutexLocker lock(&m_queueMutex);
		m_messages.enqueue(p);
	}
	emit newMessage();
}
